import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import LunaServer.core.LunaServer;
import LunaServer.routing.Route;
import LunaServer.logging.Logger;

/**
 * 登录路由处理器
 * 处理/login路径的请求
 */
public class LoginRoute implements Route {

    private final LunaServer server;
    private final Logger logger = Logger.getInstance();

    public LoginRoute(LunaServer server) {
        this.server = server;
    }

    /**
     * 处理HTTP请求
     * 
     * @param exchange HttpExchange对象
     * @return 响应内容
     */
    public String handleRequest(HttpExchange exchange) throws IOException {
        String response = "";
        int responseCode = 200;
        
        if ("POST".equals(exchange.getRequestMethod())) {
            try {
                // 读取请求体
                String requestBody = "";
                try (InputStream is = exchange.getRequestBody()) {
                    requestBody = new String(is.readAllBytes(), StandardCharsets.UTF_8);
                }
                
                logger.info("Login request received with body: " + requestBody);
                
                // 解析登录数据
                Gson gson = new Gson();
                Map<String, String> loginData = gson.fromJson(requestBody, Map.class);
                
                // 获取登录信息
                String username = loginData.get("username");
                String passwordHashedSHA256 = loginData.get("passwordHashedSHA256");
                
                // 构造响应
                Map<String, Object> result = new HashMap<>();
                
                // 实际的登录验证（查询数据库）
                Map<String, Object> userData = validateUser(username, passwordHashedSHA256);
                if (userData != null) {
                    logger.info("User login successful: " + username);
                    result.put("code", "200");
                    result.put("token", "token_for_" + username); // 示例token
                    result.put("userData", userData);
                } else {
                    responseCode = 401;
                    logger.warn("User login failed: " + username);
                    result.put("code", "401");
                    result.put("error", "用户名或密码错误");
                }
                
                result.put("time", Instant.now().toString());
                response = gson.toJson(result);
                
                // 设置响应头
                exchange.getResponseHeaders().set("Content-Type", "application/json");
            } catch (Exception e) {
                handleNotFound(exchange);
            }
        } else {
            handleMethodNotAllowed(exchange);
        }
        
        // 发送响应
        exchange.sendResponseHeaders(responseCode, response.getBytes(StandardCharsets.UTF_8).length);
        logger.info("Login request processed with response code: " + responseCode);
        return response;
    }
    
    /**
     * 验证用户凭据
     * 
     * @param username 用户名
     * @param passwordHashedSHA256 SHA256哈希后的密码
     * @return 用户数据，如果验证失败则返回null
     */
    private Map<String, Object> validateUser(String username, String passwordHashedSHA256) {
        // 从LunaServer实例获取数据库连接参数
        String dbUrl = server.getDbUrl();
        String dbUser = server.getDbUser();
        String dbPass = server.getDbPass();

        String sql = "SELECT username, age, is_active FROM users WHERE username = ? AND password = ?";

        try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
            PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, username);
            pstmt.setString(2, passwordHashedSHA256);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    Map<String, Object> userData = new HashMap<>();
                    userData.put("userName", rs.getString(1));  // 使用索引而不是字段名
                    userData.put("userLevel", rs.getInt(2));    // 使用索引而不是字段名
                    userData.put("isVIP", rs.getBoolean(3));    // 使用索引而不是字段名
                    return userData;
                }
            }

        } catch (SQLException e) {
            logger.error("Database error during login: " + e.getMessage());
            e.printStackTrace();
        }
        
        return null; // 验证失败
    }
}